package com.itxiuyixiu.tools.qiniuyun;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 黄磊
 * @date 2020/4/30
 */
public class QiniuyunTemplateServiceImpl implements QiniuyunTemplateService {
    Logger logger = LoggerFactory.getLogger(getClass());
    private final Auth auth;
    private final QiniuyunProperties properties;
    private final StringMap uploadPolicy;

    public QiniuyunTemplateServiceImpl(QiniuyunProperties properties) {
        this.properties = properties;
        this.auth = auth();
        uploadPolicy = uploadPolicy();
    }

    public Auth auth() {
        return Auth.create(properties.getAccessKey(), properties.getSecretKey());
    }

    public StringMap uploadPolicy() {
        StringMap map = new StringMap();
        map.put("scope", properties.getBucket());
        map.put("deadline", properties.getExpireSeconds());
        // 限制上传文件类型为图片
        map.put("mimeLimit", "image/*");
        // 限制大小为5M 5*1024*1024
        map.put("fsizeLimit", 5242880);
        return map;
    }

    /**
     * 获取凭证
     * <p>
     * 获取凭证以后还需要前端上传，最起码需要 tokne、key 两个值
     * https://developer.qiniu.com/kodo/manual/1272/form-upload
     *
     * @return 凭证
     */
    @Deprecated
    @Override
    public String getUploadToken() {
        return auth.uploadToken(properties.getBucket(), null, properties.getExpireSeconds(), uploadPolicy);
    }

    @Override
    public String getUploadToken(String key) {
        StringMap map = new StringMap();
        map.put("scope", properties.getBucket()+":"+key);
        map.put("deadline", properties.getExpireSeconds());
        // 限制上传文件类型为图片
        map.put("mimeLimit", "image/*");
        // 限制大小为5M 5*1024*1024
        map.put("fsizeLimit", 5242880);
        return auth.uploadToken(properties.getBucket(), key, properties.getExpireSeconds(), uploadPolicy);
    }

    @Override
    public boolean deleteFile(String key) {
        Configuration cfg = new Configuration(Zone.zone0());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        for (int i = 0; i < 3; i++) {
            try {
                bucketManager.delete(properties.getBucket(), key);
                return true;
            } catch (QiniuException ex) {
                logger.error("删除七牛云文件失败，错误代码：" + ex.code() + "，错误信息：" + ex.response.toString(), ex);
            }
        }
        return false;
    }
}
